package com.hmdp.service.impl;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.CacheClient;
import com.hmdp.utils.RedisData;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import static com.hmdp.utils.RedisConstants.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {

    @Resource
    private StringRedisTemplate stringRedisTemplate;

    @Resource
    private CacheClient cacheClient;

    //自定义线程池
    private static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);

    @Override
    public Result queryById(Long id) throws InterruptedException {
        //缓存穿透
        /* Shop shop = queryWithPassThrough(id);*/
        /*Shop shop = cacheClient.queryWithPassThrough(CACHE_SHOP_KEY, id, Shop.class, 10L, TimeUnit.SECONDS,
                id2-> getById(id));//或者this::getbyid*/


        //利用互斥锁来解决缓存击穿
        /*Shop shop = queryWithMutex(id);*/

        //利用逻辑过期来解决缓存击穿
        /*Shop shop = queryWithLogicalExpire(id);*/
         Shop shop = cacheClient.queryWithLogicalExpire(CACHE_SHOP_KEY, id, Shop.class, 10L, TimeUnit.SECONDS, this::getById);
        if (shop == null) {
            return Result.fail("店铺不存在");
        }
        //返回
        return Result.ok(shop);

    }

    /*
     *利用逻辑过期来解决缓存击穿
     * */
    public Shop queryWithLogicalExpire(Long id) {
        String key = CACHE_SHOP_KEY + id;

        //1.从redis查询商铺缓存
        String shopJsonStr = stringRedisTemplate.opsForValue().get(key);

        //2.判断是否存在
        if (StrUtil.isNotBlank(shopJsonStr)) {//null "" 都是false
            //未命中返回
            return null;
        }

        //4.命中,将json反序列化
        RedisData redisData = JSONUtil.toBean(shopJsonStr, RedisData.class);
        Shop shop = JSONUtil.toBean((JSONObject) redisData.getData(), Shop.class);
        LocalDateTime expireTime = redisData.getExpireTime();
        //5.判断是否过期
        if (expireTime.isAfter(LocalDateTime.now())) {
            //5.1未过期,直接返回
            return shop;
        }

        //5.2过期则缓存重建
        //6.缓存重建,
        //6.1获取互斥锁
        String lock = LOCK_SHOP_KEY + id;
        boolean isLock = tryLock(lock);

        if (isLock) {
            //6.2成功,开启独立线程来缓存重建
            CACHE_REBUILD_EXECUTOR.submit(() -> {
                try {
                    //缓存重建
                    saveShop2Redis(id, 20L);
                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    //释放锁
                    unLock(lock);
                }
            });

        }

        //6.3返回商铺信息
        return shop;
    }


    /*
     * 利用互斥锁解决缓存击穿
     * */
    public Shop queryWithMutex(Long id) throws InterruptedException {
        String key = CACHE_SHOP_KEY + id;

        //1.从redis查询商铺缓存
        String shopJsonStr = stringRedisTemplate.opsForValue().get(key);

        //2.判断是否存在
        if (StrUtil.isNotBlank(shopJsonStr)) {//null "" 都是false
            //3.存在,直接返回
            //根据json字符串获取对象
            Shop shop = JSONUtil.toBean(shopJsonStr, Shop.class);
            return shop;
        }
        //判断命中的是否是空值
        if (shopJsonStr != null) {//从上面下来只有两种情况null 或者""
            //空值的话返回错误信息
            return null;
        }
        //4.实现缓存重建

        //4.1获取互斥锁
        String lock = LOCK_SHOP_KEY + id;
        boolean isLock = tryLock(lock);

        //4.2判断是否获取成功
        if (!isLock) {
            //4.3失败则休眠充实
            Thread.sleep(50);
            return queryWithMutex(id);
        }


        //4.4成功,根据id查询数据库
        //模拟缓存重建延时
        Thread.sleep(200);
        Shop shop = getById(id);
        //5.数据库不存在,返回错误
        if (shop == null) {
            //将空值写入redis
            stringRedisTemplate.opsForValue().set(key, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
            return null;
        }
        //6.存在,写入redis,设置超时时间.超时剔除策略
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop), CACHE_SHOP_TTL, TimeUnit.MINUTES);
        //7.删除锁
        unLock(lock);
        //8.返回
        return shop;
    }

    /*
     * 解决缓存穿透
     * */
    /*public Shop queryWithPassThrough(Long id) {
        String key = CACHE_SHOP_KEY + id;

        //1.从redis查询商铺缓存
        String shopJsonStr = stringRedisTemplate.opsForValue().get(key);

        //2.判断是否存在
        if (StrUtil.isNotBlank(shopJsonStr)) {//null "" 都是false
            //3.存在,直接返回
            //根据json字符串获取对象
            Shop shop = JSONUtil.toBean(shopJsonStr, Shop.class);
            return shop;
        }

        //判断命中的是否是空值
        if (shopJsonStr != null) {//从上面下来只有两种情况null 或者""
            //空值的话返回错误信息
            return null;
        }


        //4.不存在,根据id查询数据库
        Shop shop = getById(id);
        //5.数据库不存在,返回错误
        if (shop == null) {
            //将空值写入redis
            stringRedisTemplate.opsForValue().set(key, "", CACHE_NULL_TTL, TimeUnit.MINUTES);
            return null;
        }
        //6.存在,写入redis,设置超时时间.超时剔除策略
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(shop), CACHE_SHOP_TTL, TimeUnit.MINUTES);
        //7.返回
        return shop;
    }*/

    /*
     * 获取锁
     * */
    private boolean tryLock(String key) {
        Boolean aBoolean = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", LOCK_SHOP_TTL, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(aBoolean);
    }


    /*
     * 删除锁
     * */
    private void unLock(String key) {
        stringRedisTemplate.delete(key);
    }


    /*
     * 存储店铺信息到redis(有逻辑过期时间)
     * */
    public void saveShop2Redis(Long id, Long expireSeconds) throws InterruptedException {
        //模拟缓存重建延时
        Thread.sleep(200);
        //1.查询店铺数据
        Shop shop = getById(id);
        //2.封装逻辑过期时间
        RedisData redisData = new RedisData();
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireSeconds));
        //3.写入redis
        stringRedisTemplate.opsForValue().set(CACHE_SHOP_KEY + id, JSONUtil.toJsonStr(redisData));
    }

    /*
     * 更新店铺信息主动更新缓存
     * */
    @Transactional
    public Result updates(Shop shop) {

        Long id = shop.getId();
        if (id == null) {
            return Result.fail("店铺id不能为空");
        }

        //更新数据库
        updateById(shop);

        //删除缓存
        stringRedisTemplate.delete(CACHE_SHOP_KEY + id);

        return Result.ok();
    }
}
